package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.model.old.Result;
import com.cardbaobao.cardbabyclient.ui.activity.base.SwipeBackActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.model.LoansTop;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Description:
 * Created by FHW
 * on 2017/7/3
 */

public class LoansDetailActivity extends SwipeBackActivity implements View.OnClickListener {
    private static final int CODE_REQUEST_LOGIN=100;
    public static final String LOANS_ID_S = "loansId";
    public static final String LOANS_NAME_S = "loansName";
    public static final String FROM_PAGE_S = "fromPage";
    public static final String CAN_ONLY_VIEW_B = "canOnlyView";
    @BindView(R.id.ll_back_white)
    LinearLayout ll_back_white;
    @BindView(R.id.iv_collect)
    ImageView iv_collect;
    @BindView(R.id.iv_detail_news)
    ImageView iv_detail_news;

    @BindView(R.id.tv_title_white)
    TextView tv_title_white;

    @BindView(R.id.tv_loans_limit)
    TextView tv_loans_limit;
    @BindView(R.id.tv_loans_mon_rate)
    TextView tv_loans_mon_rate;

    @BindView(R.id.tv_loan)
    TextView tv_loan;
    @BindView(R.id.tv_agreement)
    TextView tv_agreement;
    private String mLoansId = "";
    private String mLoansName = "";
    private String mFromPage = "";
    private boolean mCanOnlyView = false;
    private boolean isCollected;

    private LoansTop mLoansTop;

    @Override
    protected void onResume() {
        super.onResume();
        GoogleAnalyticsUtil.setScreenName(Google.LOANS_DETAIL);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        mCurrentPageId= Self.Page.app_loan_detail_page;

        mLoansId = getIntent().getStringExtra(LOANS_ID_S);
        mLoansName = getIntent().getStringExtra(LOANS_NAME_S);
        mFromPage = getIntent().getStringExtra(FROM_PAGE_S);
        mCanOnlyView = getIntent().getBooleanExtra(CAN_ONLY_VIEW_B, false);

        tv_title_white.setText(mLoansName);

        ll_back_white.setOnClickListener(this);
        iv_collect.setOnClickListener(this);
        iv_detail_news.setOnClickListener(this);
        tv_loan.setOnClickListener(this);
        tv_agreement.setOnClickListener(this);

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        getLoansTopData();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_loans_detail;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if (requestCode==CODE_REQUEST_LOGIN) {
                mController.detailPageApplyLoans("0", mLoansId, mLoansName, mFromPage);
            }
        }
    }

    /**
     * 获取头部的贷款信息
     */
    public void getLoansTopData() {
        showProgressDialog(false);
        Observable<String> observable;
        if(mApplication.getIsLogin()&&mApplication.getUser()!=null){
            observable= Api.getLoanDetail(mLoansId,String.valueOf(mApplication.getUser().getID()));
        }else{
            observable= Api.getLoanDetail(mLoansId,null);
        }
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                dismissProgressDialog();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                mLoansTop = JsonUtil.getJavaBean(s, LoansTop.class);
                setLoansView();
            }
        });
    }

    /**
     * 收藏
     */
    protected void addCollect(String productId) {
        if (mApplication.getIsLogin() && mApplication.getUser() != null) {
            Observable<String> observable=
                    Api.collect(String.valueOf(mApplication.getUser().getID()),productId,"ZCC0102");
            observable.subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.showToast(ApplicationHelper.
                            getApplicationContext().
                            getString(R.string.string_request_server_fail));
                }

                @Override
                public void onNext(String s) {
                    Result result = JsonUtil.getResult(s, Result.class);
                    if(result !=null&& Result.SUCCESS.equals(result.getResult())){
                        //收藏成功
                        ToastUtil.showToastOnScreenCenter("收藏成功");
                        iv_collect.setImageResource(R.mipmap.icon_collected);
                        isCollected = true;
                    }else{
                        //收藏失败
                        ToastUtil.showToastOnScreenCenter("收藏失败");
                    }
                }
            });
        } else {
            ToastUtil.showToast("未登录无法收藏");
        }
    }

    /**
     * 取消收藏
     */
    protected void cancelCollect(String productId) {
        if (mApplication.getIsLogin() && mApplication.getUser() != null) {
            Observable<String> observable=
                    Api.unCollect(String.valueOf(mApplication.getUser().getID()),productId,"ZCC0102");
            observable.subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.showToast(ApplicationHelper.
                            getApplicationContext().
                            getString(R.string.string_request_server_fail));
                }

                @Override
                public void onNext(String s) {
                    Result result = JsonUtil.getResult(s, Result.class);
                    if(result !=null&& Result.SUCCESS.equals(result.getResult())){
                        //取消收藏成功
                        ToastUtil.showToastOnScreenCenter("取消收藏");
                        iv_collect.setImageResource(R.mipmap.icon_collect);
                        isCollected = false;
                    }else{
                        ToastUtil.showToastOnScreenCenter("操作失败");
                    }
                }
            });
        } else {
            ToastUtil.showToast("未登录无法收藏");
        }
    }

    private String getStringValue(String value) {
        if (TextUtils.isEmpty(value)) {
            return "0";
        } else {
            return value;
        }
    }

    public static String doubleTrans(double num) {
        if (num % 1.0 == 0) {
            return String.valueOf((long) num);
        }
        return String.valueOf(num);
    }

    private void setLoansView() {
        if (mLoansTop.getLoansLimitMax() >= 10) {
            tv_loans_limit.setText(doubleTrans(mLoansTop.getLoansLimitMax()) + " 万");
        } else {
            tv_loans_limit.setText((int) (mLoansTop.getLoansLimitMax() * 10000) + "");
        }

        String monthRate = getStringValue(mLoansTop.getMonthRateTxt());
        tv_loans_mon_rate.setText(monthRate);

        //是否已被收藏
        if (!TextUtils.isEmpty(mLoansTop.getMfID())) {
            if (mApplication.getIsLogin()) {
                //有值表示被收藏
                iv_collect.setImageResource(R.mipmap.icon_collected);
                isCollected = true;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_back_white:
                finish();
                break;
            case R.id.iv_collect:
                //收藏
                if (isCollected) {
                    //已收藏
                    cancelCollect(mLoansId);
                    SelfUtils.buriedClickData(Self.Action.app_click_cancel_collect_loan,
                            Self.Action.app_click_cancel_collect_loan_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, Google.ACTION_COLLECT_LOAN);
                } else {
                    //未收藏
                    addCollect(mLoansId);
                    SelfUtils.buriedClickData(Self.Action.app_click_collect_loan,
                            Self.Action.app_click_collect_loan_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, Google.ACTION_COLLECT_LOAN_CAN);
                }
                break;
            case R.id.iv_detail_news:
                initIntent();
                SelfUtils.buriedClickData(Self.Action.app_click_loan_intro,
                        Self.Action.app_click_loan_intro_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S,
                        URLUtil.LOAN_INTRO + "?id=" + mLoansId);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S, mLoansName);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 1);
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                mContext.startActivity(mIntent);
                break;
            case R.id.tv_loan:
                //申请
                if(mApplication.getIsLogin()){
                    SelfUtils.buriedClickData(Self.Action.app_click_apply_loan,
                            Self.Action.app_click_apply_loan_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    mController.detailPageApplyLoans("0", mLoansId, mLoansName, mFromPage);
                }else{
                    Intent intent=new Intent(mContext,AccountLoginActivity.class);
                    intent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                            Constant.PLY010202);
                    startActivityForResult(intent,CODE_REQUEST_LOGIN);
                    overridePendingTransition(R.anim.activity_in_bottom, R.anim.activity_out_top);
                }
                break;
            case R.id.tv_agreement:
                initIntent();
                SelfUtils.buriedClickData(Self.Action.app_click_loan_agreement,
                        Self.Action.app_click_loan_agreement_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S, "卡宝宝服务协议");
                mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S, URLUtil.REGISTRATION_AGREEMENT);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 2);
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                startActivity(mIntent);
                break;
        }
    }
}
